package com.example.zhaoy.rebook.net;


import com.alibaba.fastjson.JSON;
import com.example.zhaoy.rebook.dao.Book;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by asus on 2017/3/18 0018.
 */

public class DouBanService {
    public Book serachBook(String isbn) {
        try {
            URL url = new URL("https://api.douban.com/v2/book/"+isbn);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() == 200) {
                InputStream in = new BufferedInputStream(connection.getInputStream());
                String json = readInStream(in);
                System.out.print(json);
                Book book = JSON.parseObject(json, Book.class);

                return book;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Book();
    }

    private String readInStream(InputStream in) throws IOException {
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        StringBuilder bulider = new StringBuilder();
        // 从流中按字节读取内容，到文件尾部时read方法将返回-1
        while ((bytesRead = in.read(buffer)) != -1) {
            // 将读取的字节转为字符串对象
            String chunk = new String(buffer, 0, bytesRead);
            bulider.append(chunk);
        }
        return bulider.toString();
    }
<<<<<<< HEAD
=======
    public static void main(String[] args) {
        System.out.println(new DouBanService().serachBook("1003078").toString());
    }
>>>>>>> daffbc6725766803ea43c523d2665d5015e08ae9

}
